package com.egao.common.manage.school;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.egao.common.component.minio.config.MinioBucket;
import com.egao.common.component.minio.service.MinioService;
import com.egao.common.core.Constants;
import com.egao.common.core.annotation.ApiPageParam;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.utils.SendSmsUtil;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.company.constants.CheckRecordConstants;
import com.egao.common.module.company.constants.PreachConstants;
import com.egao.common.module.company.entity.Company;
import com.egao.common.module.company.entity.Preach;
import com.egao.common.module.company.entity.PreachWorker;
import com.egao.common.module.company.entity.vo.PreachFormVO;
import com.egao.common.module.company.entity.vo.PreachListVO;
import com.egao.common.module.company.entity.vo.PreachWorkerForm;
import com.egao.common.module.company.service.CompanyService;
import com.egao.common.module.company.service.PreachService;
import com.egao.common.module.company.service.PreachWorkerService;
import com.egao.common.module.push.service.PositionMatchingService;
import com.egao.common.module.system.constants.EmailConstants;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.service.EmailService;
import com.egao.common.module.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 学校宣讲会管理
 * @author dl
 */
@Api(tags = "学校宣讲会管理")
@RestController
@RequestMapping("${api}")
public class SchoolPreachController extends BaseController {

    @Autowired
    private PreachService preachService;

    @Autowired
    private PositionMatchingService positionMatchingService;

    @Autowired
    private PreachWorkerService preachWorkerService;

    @Autowired
    private MinioService minioService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private UserService userService;

    @PreAuthorize("hasAuthority('school:preach:list')")
    @ApiOperation(value = "宣讲会信息", notes = "未审核状态升序 创建时间倒序")
    @OperLog(value = "宣讲会信息", desc = "分页查询宣讲会信息")
    @ApiPageParam
    @GetMapping("/school/preach/page")
    public PageResult<PreachListVO> page(HttpServletRequest request) {
        PageParam<PreachListVO> pageParam = new PageParam<>(request);
        return new PageResult<>(preachService.listPage(pageParam), pageParam.getTotal());
    }

    @PreAuthorize("hasAuthority('school:preach:check')")
    @OperLog(value = "添加宣讲会信息", desc = "添加宣讲会信息", result = true)
    @ApiOperation(value = "添加宣讲会信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preachFormVO", value = "preachFormVO", required = true, dataType = "PreachFormVO")
    })
    @PostMapping("/school/preach/save")
    public JsonResult save(@Valid @RequestBody PreachFormVO preachFormVO) {
        preachFormVO.setCreateBy(getLoginUserId());
        return preachService.savePreachSchool(preachFormVO);
    }

    @PreAuthorize("hasAuthority('school:preach:check')")
    @OperLog(value = "审核宣讲会信息", desc = "审核宣讲会信息", result = true)
    @ApiOperation(value = "审核宣讲会信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preachFormVO", value = "preachFormVO", required = true, dataType = "PreachFormVO")
    })
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/school/preach/check")
    public JsonResult check(@Valid @RequestBody PreachFormVO preachFormVO) {
        preachFormVO.setCheckUserId(getLoginUserId());

        JsonResult jsonResult = preachService.checkPreach(preachFormVO);
        if (Constants.RESULT_ERROR_CODE == jsonResult.getCode()) {
            return jsonResult;
        }

        if ("1".equals(preachFormVO.getState())) {
            new SendSmsUtil().send(preachFormVO.getLeaderMobile(),"SMS_465399589");
        }
        if ("2".equals(preachFormVO.getState())) {
            new SendSmsUtil().send(preachFormVO.getLeaderMobile(),"SMS_472420325");
        }
        return jsonResult;
    }

    @PreAuthorize("hasAuthority('school:preach:check')")
    @OperLog(value = "修改宣讲会信息", desc = "审核宣讲会信息", result = true)
    @ApiOperation(value = "修改宣讲会信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preachFormVO", value = "preachFormVO", required = true, dataType = "PreachFormVO")
    })
    @PutMapping("/school/preach/update")
    public JsonResult update(@Valid @RequestBody PreachFormVO preachFormVO) {
        return preachService.updatePreachSchool(preachFormVO);
    }

    @PreAuthorize("hasAuthority('school:preach:delete')")
    @OperLog(value = "删除宣讲会信息", desc = "删除宣讲会信息", result = true)
    @ApiOperation(value = "删除宣讲会信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preachFormVO", value = "preachFormVO", required = true, dataType = "PreachFormVO")
    })
    @PutMapping("/school/preach/delete")
    public JsonResult deletePreach(@RequestBody PreachFormVO preachFormVO) {
        return preachService.removePreach(preachFormVO);
    }

    @PreAuthorize("hasAuthority('school:preach:detail')")
    @ApiOperation(value = "获取宣讲会信息详情")
    @OperLog(value = "获取宣讲会信息详情", desc = "获取宣讲会信息详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "宣讲会信息id", required = true, dataType = "int")
    })
    @GetMapping("/school/preach/detail")
    public JsonResult detail(Integer id) {
        return preachService.detail(id);
    }

    @PreAuthorize("hasAuthority('school:preach:detail')")
    @ApiOperation(value = "获取职位推荐统计")
    @OperLog(value = "获取职位推荐统计", desc = "获取职位推荐统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "宣讲会信息id", required = true, dataType = "int")
    })
    @GetMapping("/school/preach/push-total")
    public JsonResult getTotal(Integer id) throws IOException {
        return positionMatchingService.getTotal(id, CheckRecordConstants.CHECK_PREACH);
    }

    @PreAuthorize("hasAuthority('school:preach:list')")
    @ApiOperation(value = "宣讲会参与人员集合")
    @GetMapping("/school/preach/worker")
    public JsonResult worker(Integer id) {
        Preach preach = preachService.getById(id);
        preach.setApproachedImgPreview(minioService.getPreSignedObjectUrl(MinioBucket.MINIO_PREACH, preach.getApproachedImg()));

        List<PreachWorker> list =
                preachWorkerService.list(new LambdaQueryWrapper<PreachWorker>().eq(PreachWorker::getPreachId, id).orderByAsc(PreachWorker::getId));

        for (PreachWorker preachWorker : list) {
            preachWorker.setTripImgPreview(minioService.getPreSignedObjectUrl(MinioBucket.MINIO_PREACH, preachWorker.getTripImg()));
            preachWorker.setDetectionImgPreview(minioService.getPreSignedObjectUrl(MinioBucket.MINIO_PREACH, preachWorker.getDetectionImg()));
            preachWorker.setThreeImgPreview(minioService.getPreSignedObjectUrl(MinioBucket.MINIO_PREACH, preachWorker.getThreeImg()));
        }

        PreachWorkerForm preachWorkerForm = new PreachWorkerForm();
        preachWorkerForm.setPreach(preach);
        preachWorkerForm.setPreachWorkerList(list);
        return JsonResult.ok().setData(preachWorkerForm);
    }

    @PreAuthorize("hasAuthority('school:preach:check')")
    @OperLog(value = "审核参与人员信息", desc = "审核参与人员信息", result = true)
    @ApiOperation(value = "审核参与人员信息")
    @PutMapping("/school/preach/check-worker")
    public JsonResult checkWorker(@Valid @RequestBody PreachFormVO preachFormVO) {
        Preach update = new Preach();
        update.setId(preachFormVO.getId());
        update.setWorkerState(preachFormVO.getWorkerState());
        update.setWorkerStateContent(preachFormVO.getWorkerStateContent());
        if (preachService.updateById(update)) {
            return JsonResult.ok("审核成功");
        }

        return JsonResult.error("审核失败");
    }

    @PreAuthorize("hasAuthority('school:preach:check')")
    @OperLog(value = "更新录入车牌状态", desc = "更新录入车牌状态", result = true)
    @ApiOperation(value = "更新录入车牌状态")
    @PutMapping("/school/preach/car-state")
    public JsonResult carState(@Valid @RequestBody PreachFormVO preachFormVO) {
        Preach update = new Preach();
        update.setId(preachFormVO.getId());
        update.setCarState(PreachConstants.CAR_STATE_SUCCESS);
        if (preachService.updateById(update)) {
            return JsonResult.ok("更新成功");
        }

        return JsonResult.error("更新失败");
    }

    @PreAuthorize("hasAuthority('school:preach:check')")
    @OperLog(value = "宣讲会信息", desc = "导出宣讲会信息")
    @ApiOperation(value = "导出宣讲会信息")
    @GetMapping("/school/preach/export")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> pageParam = new PageParam<>(request).getNoPageParam();
        preachService.exportExcel(pageParam, response);
    }



}
